<?php
if (!isset($_POST['value'])
    || !isset($_POST['companyId'])
) {
    echo("Missing parameters from add");
    exit();
}
$value = $_POST['value'];
$companyId = $_POST['companyId'];

// import database connection variables and connectToMysql method
require_once __DIR__ . '/db_config.php';

$mysqli = connectToMysql();

$query = "INSERT INTO rating ( value, companyId) VALUES ( '$value', '$companyId')";
if ($result = $mysqli->query($query)) {
    $ratingId = json_encode($mysqli->insert_id, JSON_NUMERIC_CHECK);
    $query = "select avg(r.value) as average_rage  from rating r where r.companyId = " . $companyId;
    echo $query;
    echo "\n";
    if ($result = $mysqli->query($query)) {
        $row = $result->fetch_row();
        $output = array_map('utf8_encode', $row);
        $ratingSum = $output[0];

        $query = "Update company set averageRating = '$ratingSum' where id = " . $companyId;
        echo $query;
        if ($result =$mysqli->query($query)){

        } else {
            print mysqli_error($mysqli);
        }
    } else {
        print mysqli_error($mysqli);
    }

    echo $ratingId;
} else {
    print mysqli_error($mysqli);
}
/* close connection */
$mysqli->close();
